package com.lancoo.tyjx.multichatroom.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lancoo.tyjx.multichatroom.R;
import com.lancoo.tyjx.multichatroom.adapter.ChatAdapter;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.db.MsgDbHelper;
import com.lancoo.tyjx.multichatroom.expression.ExpressionListener;
import com.lancoo.tyjx.multichatroom.expression.ExpressionView;
import com.lancoo.tyjx.multichatroom.model.ChatItem;
import com.lancoo.tyjx.multichatroom.utils.DateUtil;
import com.lancoo.tyjx.multichatroom.utils.FileUtil;
import com.lancoo.tyjx.multichatroom.utils.ImageUtil;
import com.lancoo.tyjx.multichatroom.utils.SoftKeyBoardListener;
import com.lancoo.tyjx.multichatroom.utils.Tool;
import com.lancoo.tyjx.multichatroom.view.MyListView;
import com.lancoo.tyjx.multichatroom.view.MyListView.OnRefreshListener;
import com.lancoo.tyjx.multichatroom.view.RecordButton;
import com.lancoo.tyjx.multichatroom.view.RecordButton.OnFinishedRecordListener;
import com.lancoo.tyjx.multichatroom.xmpp.XmppMsgType;
import com.lancoo.tyjx.multichatroom.xmpp.XmppTool;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("NewApi")
public class RoomChatActivity extends AppCompatActivity implements OnClickListener {
    private ImageView leftBtn, rightBtn, sendBtn, picBtn, expBtn, moreBtn, upvotebtn;
    private Button takePicBtn, chosePicBtn, fileBtn, adrBtn;
    private LinearLayout moreLayout;
    private RecordButton recordBtn;
    private ExpressionView expView;
    private EditText msgText;
    private TextView titleView;
    private MyListView listView;
    private String chatName; // 群的时候是群名称
    private int chatType = 0;
    private List<ChatItem> chatItems = new ArrayList<ChatItem>();
    private ChatAdapter adapter;
    private UpMessageReceiver mUpMessageReceiver;
    private boolean isupvote;
    private String topickName;
    private String chatRoomID;
    private String liveId;
    public static RoomChatActivity instance = null;
    private static final String TAG = "RoomChatActivity";
//	public LocationClient mLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		SDKInitializer.initialize(getApplicationContext());

        setContentView(R.layout.activity_room_chat);

        instance = this;
        chatRoomID = getIntent().getStringExtra("roomId");
        topickName = getIntent().getStringExtra("topickName");
        chatName = getIntent().getStringExtra("chatName");
        liveId = getIntent().getStringExtra("liveId");
        chatType = getIntent().getIntExtra("chatType", ChatItem.CHAT);
        System.out.println("RoomChatActivity.onCreate()===========" + chatType);

        initView();
        initData();
        initBaiduLocation();
        titleView.setText(topickName);
    }

    private void initData() {
        chatItems = MsgDbHelper.getInstance(getApplicationContext())
                .getChatMsg(chatName);
        adapter.initDataSource(chatItems);
        adapter.notifyDataSetChanged();
        listView.setSelection(adapter.getCount() + 1);

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                {
                    expView.setVisibility(View.GONE);
                }
                // Determine the voice
                if (msgText.getVisibility() == View.GONE) {
                    msgText.setVisibility(View.VISIBLE);
                    recordBtn.setVisibility(View.GONE);
                    if ("".equals(msgText.getText().toString()))
                        sendBtn.setImageResource(R.drawable.icon_voice);
                    else
                        sendBtn.setImageResource(R.drawable.icon_send_w);
                }
            }

            @Override
            public void keyBoardHide(int height) {

            }
        });
    }

    public void sendBoardToRoom(String msgBody, int sendState) {
        ChatItem chatItem = new ChatItem(chatType, chatName, chatName + "@conference." + Constants.SERVER_HOST,
                "", msgBody, DateUtil.now_MM_dd_HH_mm_ss(), 1, sendState);
        if (sendState == 0) {//正在发送
            chatItems.add(chatItem);
            adapter.initDataSource(chatItems);
            adapter.notifyDataSetChanged();
            listView.setSelection(adapter.getCount() + 1);
        } else {//发送失败
            MsgDbHelper.getInstance(MyApplication.getInstance()).saveChatMsg(chatItem);
            MyApplication.getInstance().sendBroadcast(new Intent("ChatNewMsg"));
        }
    }

    private void initBaiduLocation() {
//		mLocationClient = new LocationClient(this.getApplicationContext());
//		LocationClientOption option = new LocationClientOption();
//		option.setOpenGps(true);// 打开gps
//		option.setCoorType("bd09ll"); // 设置坐标类型
//		option.setScanSpan(1000);
//		mLocationClient.setLocOption(option);
//		mLocationClient.registerLocationListener(new BDLocationListener() {
//			@Override
//			public void onReceiveLocation(BDLocation location) {
//				// Receive Location
//				String addr = "[/a0," + location.getLatitude() + ","
//						+ location.getLongitude();
//				try {
//					XmppTool.getInstance().sendMsg(addr, chatType);
//				} catch (Exception e) {
//					autoSendIfFail(addr);
//					e.printStackTrace();
//				}
//				Log.i("BaiduLocationApiDem", addr);
//				Tool.initToast(getApplicationContext(), addr);
//				mLocationClient.stop();
//				MyApplication.lat = location.getLatitude();
//				MyApplication.lon = location.getLongitude();
//			}
//		});
    }

    private void initView() {
        leftBtn = (ImageView) findViewById(R.id.leftBtn);
        leftBtn.setOnClickListener(this);
        rightBtn = (ImageView) findViewById(R.id.rightBtn);
        rightBtn.setOnClickListener(this);
        sendBtn = (ImageView) findViewById(R.id.sendBtn);
        sendBtn.setOnClickListener(this);
        expBtn = (ImageView) findViewById(R.id.expBtn);
        expBtn.setOnClickListener(this);
        moreBtn = (ImageView) findViewById(R.id.moreBtn);
        moreBtn.setOnClickListener(this);
        takePicBtn = (Button) findViewById(R.id.takePicBtn);
        takePicBtn.setOnClickListener(this);
        chosePicBtn = (Button) findViewById(R.id.chosePicBtn);
        chosePicBtn.setOnClickListener(this);
        adrBtn = (Button) findViewById(R.id.adrBtn);
        adrBtn.setOnClickListener(this);
        upvotebtn = (ImageView) findViewById(R.id.iv_upvoteoption);
        upvotebtn.setOnClickListener(this);

        moreLayout = (LinearLayout) findViewById(R.id.moreLayout);
        recordBtn = (RecordButton) findViewById(R.id.recordBtn);
        expView = (ExpressionView) findViewById(R.id.expView);
        msgText = (EditText) findViewById(R.id.msgText);
        titleView = (TextView) findViewById(R.id.titleView);
        expView = (ExpressionView) findViewById(R.id.expView);
        listView = (MyListView) findViewById(R.id.listView);

        recordBtn.setActivity(this);

        boolean isUpVote = Constants.voteState.get(liveId);
        if (isUpVote) {
            upvotebtn.setBackgroundResource(R.drawable.chat_upvote_has);
        } else {
            upvotebtn.setBackgroundResource(R.drawable.chat_upvote_not);
        }

        adapter = new ChatAdapter(getApplicationContext(), chatName, null);
        adapter.initDataSource(chatItems);
        listView.setAdapter(adapter);
        listView.setonRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(0);
                    }
                }).start();
            }
        });

        msgText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                expView.setVisibility(View.GONE);
            }
        });
        msgText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if ("".equals(msgText.getText().toString())) {
                    sendBtn.setImageResource(R.drawable.icon_voice);
                } else
                    sendBtn.setImageResource(R.drawable.icon_send_w);
            }
        });

        recordBtn.setOnFinishedRecordListener(new OnFinishedRecordListener() {
            @Override
            public void onStartRecord() {
                adapter.stopPlayer();
            }

            @Override
            public void onFinishedRecord(String audioPath, int time) {
                if (audioPath != null) {
                    try {
                        sendBoardToRoom(Constants.SAVE_SOUND_PATH + "/" + FileUtil.getFileName(audioPath), 0);
                        XmppTool.getInstance().sendMsgWithParms(
                                FileUtil.getFileName(audioPath),
                                new String[]{"imgData", "Duration"},
                                new Object[]{ImageUtil
                                        .getBase64StringFromFile(audioPath), time},
                                chatType, XmppMsgType.AUDIO);
                    } catch (Exception e) {
                        autoSendIfFail(FileUtil.getFileName(audioPath),
                                new String[]{"imgData"},
                                new Object[]{ImageUtil
                                        .getBase64StringFromFile(audioPath)}, XmppMsgType.AUDIO);
                        e.printStackTrace();
                    }
                } else {
                    Tool.initToast(RoomChatActivity.this, "发送失败");
                }

            }
        });
        expView.setEditText(msgText);
        expView.setGifListener(new ExpressionListener() {
            @Override
            public void clickGif(String msg) {
                try {
                    XmppTool.getInstance().sendMsg(msg, chatType);
                    sendBoardToRoom(msg, 0);
                } catch (Exception e) {
                    autoSendIfFail(msg);
                    e.printStackTrace();
                }
            }
        });

        // 会话内容改变，接受广播
        if (mUpMessageReceiver == null)
            mUpMessageReceiver = new UpMessageReceiver();
        registerReceiver(mUpMessageReceiver, new IntentFilter("ChatNewMsg"));
        registerReceiver(mUpMessageReceiver, new IntentFilter("LeaveRoom"));

//		XmppTool.getInstance().setRecevier(chatName, chatType);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finishActivity();
    }

    public void finishActivity() {
        instance = null;
        try {
            adapter.mediaPlayer.stop();
            if (MyApplication.getInstance() != null) {
                unregisterReceiver(mUpMessageReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (chatType == ChatItem.GROUP_CHAT) {
//			XmppTool.getInstance().leaveMuc(chatName);
            // XmppTool.getInstance().closeConnection();
        }
        clearMsgCount();
        finish();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    private void clearMsgCount() {
        // 清空数据库
        // NewMsgDbHelper.getInstance(getApplicationContext()).delNewMsg(chatName);
        // MsgDbHelper.getInstance(getApplicationContext()).clear();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                listView.onRefreshComplete();
                List<ChatItem> moreChatItems = MsgDbHelper.getInstance(
                        getApplicationContext()).getChatMsgMore(
                        listView.getCount() - 1, chatName);
                for (int i = 0; i < moreChatItems.size(); i++) {
                    chatItems.add(i, moreChatItems.get(i));
                }
//				adapter.clear();
//				adapter.addAll(chatItems);
                adapter.initDataSource(chatItems);
                adapter.notifyDataSetChanged();
            }
        }
    };


    private class UpMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到廣播更新我们的界面
            if (intent.getAction().equals("LeaveRoom")) {
                finish();
            } else if (intent.getAction().equals("ChatNewMsg")) {
                initData();
            }
        }
    }

    public void onClick(View v) {


        if (v.getId() == R.id.leftBtn) {
            finishActivity();
        } else if (v.getId() == R.id.rightBtn) {
            if (chatType == ChatItem.CHAT) {
                Tool.initToast(getApplicationContext(), "FriendActivity.class");
                // intent.setClass(getApplicationContext(),
                // FriendActivity.class);
                // intent.putExtra("username", chatName);
                // startActivity(intent);
            } else if (chatType == ChatItem.GROUP_CHAT) {
                Tool.initToast(getApplicationContext(), "RoomMemActivity.class");
                // intent.setClass(getApplicationContext(),
                // RoomMemActivity.class);
                // intent.putExtra("roomName", chatName);
                // startActivity(intent);
            }
        } else if (v.getId() == R.id.sendBtn) {

            String msg = msgText.getText().toString(); // 获取text文本
            if (!msg.isEmpty()) { // 文本不为空，直接发文本消息
                try {
                    sendBoardToRoom(msg, 0);
                    XmppTool.getInstance().sendMsg(msg, chatType);
                } catch (Exception e) {
                    autoSendIfFail(msg);
                    e.printStackTrace();
                }
                msgText.setText("");
            } else if (recordBtn.getVisibility() == View.GONE) { // 文本为空，从文本输入模式切换到语音输入模式
//				requiresPermission();
                msgText.setVisibility(View.GONE);
                recordBtn.setVisibility(View.VISIBLE);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(msgText.getWindowToken(), 0);
                expView.setVisibility(View.GONE);
                sendBtn.setImageResource(R.drawable.icon_keyboard);
            } else if (msgText.getVisibility() == View.GONE) { // 文本为空，从语音输入模式切换到文本输入模式

                msgText.setVisibility(View.VISIBLE);
                recordBtn.setVisibility(View.GONE);
                sendBtn.setImageResource(R.drawable.icon_voice);
            }
        } else if (v.getId() == R.id.msgText)// 选中文本框，聊天记录弹到最后一条
        {
            expView.setVisibility(View.GONE);
            listView.setSelection(adapter.getCount()); // 去到最后一行
        } else if (v.getId() == R.id.moreBtn)// 弹出更多发送内容,选图，照相，发送位置
        {
            if (moreLayout.getVisibility() == View.GONE) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                moreLayout.setVisibility(View.VISIBLE);
                expView.setVisibility(View.GONE);
            } else {
                moreLayout.setVisibility(View.GONE);
            }
        } else if (v.getId() == R.id.takePicBtn)// 拍照
        {
            Intent intent1 = new Intent();
            CropImageActivity.isAutoSend = true;
            intent1.setClass(this, PicSrcPickerActivity.class);
            intent1.putExtra("type", PicSrcPickerActivity.TAKE_PIC);
            startActivityForResult(intent1, PicSrcPickerActivity.CROP);
        } else if (v.getId() == R.id.chosePicBtn) // 图库
        {
            Intent intent2 = new Intent();
            CropImageActivity.isAutoSend = true;
            intent2.setClass(this, PicSrcPickerActivity.class);
            intent2.putExtra("type", PicSrcPickerActivity.CHOSE_PIC);
            startActivityForResult(intent2, PicSrcPickerActivity.CROP);
        } else if (v.getId() == R.id.expBtn)// 点击表情icon
        {
            if (expView.getVisibility() == View.GONE) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                expView.setVisibility(View.VISIBLE);
                moreLayout.setVisibility(View.GONE);
            } else {
                expView.setVisibility(View.GONE);
            }
            // Determine the voice
            if (msgText.getVisibility() == View.GONE) {
                msgText.setVisibility(View.VISIBLE);
                recordBtn.setVisibility(View.GONE);
                if ("".equals(msgText.getText().toString()))
                    sendBtn.setImageResource(R.drawable.icon_voice);
                else
                    sendBtn.setImageResource(R.drawable.icon_send_w);
            }
        } else if (v.getId() == R.id.iv_upvoteoption) {
            Boolean isUpVote = Constants.voteState.get(liveId);
            if (isUpVote) {
                Constants.isupvote = false;
                upvotebtn.setBackgroundResource(R.drawable.chat_upvote_not);
                try {
                    XmppTool.getInstance().sendLikeMsg("unlike", ChatItem.GROUP_CHAT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Constants.isupvote = true;
                upvotebtn.setBackgroundResource(R.drawable.chat_upvote_has);
                try {
                    XmppTool.getInstance().sendLikeMsg("like", ChatItem.GROUP_CHAT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Constants.voteState.put(liveId, Constants.isupvote);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            switch (requestCode) { // 选图回调
                case PicSrcPickerActivity.CROP:
                    String imgName = data.getStringExtra("imgName");
                    String base64String = data.getStringExtra("base64String");
                    if (imgName != null) {
                        try {
                            sendBoardToRoom(Constants.SAVE_IMG_PATH + "/" + imgName, 0);
                            XmppTool.getInstance().sendMsgWithParms(imgName,
                                    new String[]{"imgData"},
                                    new Object[]{base64String}, chatType, XmppMsgType.PICTURE);
                        } catch (Exception e) {
                            autoSendIfFail(imgName, new String[]{"imgData"},
                                    new Object[]{base64String}, XmppMsgType.PICTURE);
                            e.printStackTrace();
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    }

    // 下面是断线发不出内容时自动重发
    public static boolean isLeaving = false;

    public void autoSendIfFail(final String msg) {
//		Tool.initToast(MyApplication.getInstance(), "发送中..");
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() { // 1秒后开始
            int count = 0;

            @Override
            public void run() {
                try {
                    count++;
                    if (!isLeaving) {
                        XmppTool.getInstance().setRecevier(chatName,
                                chatType);
                        XmppTool.getInstance().sendMsg(msg, chatType);
                        timer.cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Log.e("muc", "autosend      " + count);
                    if (count > 8) {
                        sendBoardToRoom(msg, 2);
                        Tool.initToast(MyApplication.getInstance(),
                                "发送失败");
                        timer.cancel();
                    }
                }
            }
        }, 1000, 1000);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public void autoSendIfFail(final String msg, final String[] s,
                               final Object[] obj, final XmppMsgType msgType) {
//		Tool.initToast(MyApplication.getInstance(), "发送中..");
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() { // 1秒后开始
            int count = 0;

            @Override
            public void run() {
                try {
                    count++;
                    if (!isLeaving) {
                        XmppTool.getInstance().setRecevier(chatName,
                                chatType);
                        XmppTool.getInstance().sendMsgWithParms(msg, s,
                                obj, chatType, msgType);
                        timer.cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Log.e("muc", "autosend      " + count);
                    if (count > 8) {
                        if (msg.endsWith(".jpg")) {
                            sendBoardToRoom(Constants.SAVE_IMG_PATH + "/" + msg, 2);
                        } else if (msg.endsWith(".amr") || msg.endsWith("aec")) {
                            sendBoardToRoom(Constants.SAVE_SOUND_PATH + "/" + msg, 2);
                        }
                        Tool.initToast(MyApplication.getInstance(),
                                "发送失败");
                        timer.cancel();
                    }
                }
            }
        }, 1000, 1000);
    }
}
